import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import Login from '@/views/Login.vue'
import Layout from '@/views/Layout.vue'
import FileManager from '@/views/FileManager.vue'
import SharedFiles from '@/views/SharedFiles.vue'
import UserManagement from '@/views/UserManagement.vue'
import DepartmentManagement from '@/views/DepartmentManagement.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/',
    component: Layout,
    redirect: '/files',
    children: [
      {
        path: 'files',
        name: 'FileManager',
        component: FileManager,
        meta: { title: '文件管理' }
      },
      {
        path: 'shared',
        name: 'SharedFiles',
        component: SharedFiles,
        meta: { title: '共享文件' }
      },
      {
        path: 'users',
        name: 'UserManagement',
        component: UserManagement,
        meta: { title: '用户管理', requiresAdmin: true }
      },
      {
        path: 'departments',
        name: 'DepartmentManagement',
        component: DepartmentManagement,
        meta: { title: '部门管理', requiresAdmin: true }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  
  if (to.path === '/login') {
    if (authStore.isAuthenticated) {
      next('/')
    } else {
      next()
    }
  } else {
    if (!authStore.isAuthenticated) {
      next('/login')
    } else if (to.meta.requiresAdmin && authStore.user?.role !== 'admin') {
      ElMessage.error('权限不足')
      next('/')
    } else {
      next()
    }
  }
})

export default router